Ext.define('TS.controller.Product', {
    extend: 'Ext.app.Controller',
    models: ['base.ProductModel','base.ProductClassifyModel','base.ProductBusPropertiesModel',
    'base.ProductMedicinePropertiesModel'
    ],
    stores: [
        'base.ProductStore','base.ProductClassifyStore','base.ProductManufStore'
    ],
    views: [
        'base.ProductList','base.ProductSimpleList','base.ProductSearchDialog','base.ProductClassifyTree'
        ,'base.ProductInfo','base.ProductClassifyEditer','base.ProductEditer',
        'base.ProductManufList','base.ProductManufEditer','base.ManufEditer','base.ManufNewEditer'
    ],
    init: function() {
        this.control({ 
        	'productlist':{
        		itemdblclick: this.editProd
        	},
        	'productlist':{
        		select: this.showProdProperties
        	},
        	'productlist button[action=add]': { 
	            click: this.addProd
	        },
        	'productlist button[action=upd]': { 
	            click: this.btnUpdProd
	        },
        	'productlist button[action=recycle]': { 
	            click: this.recycleProd
	        },
        	'productlist button[action=exportxls]':{
        		click: this.exportXLS
        	},
        	'productlist button[action=ref]':{
        		click: this.refProduct
        	},
        	'productlist button[action=restore]': { 
	            click: this.restoreProd
	        },
        	'productlist button[action=del]': { 
	            click: this.delProd
	        },
        	'productlist button[action=manuf]': { 
	            click: this.productManuf
	        },
        	'productinfo productlist triggerfield': { 
	            specialkey: this.searchProduct
	        },
	        'productinfo prodclassifytree button[action=add]':{
	        	click:this.addClassify
	        },
	        'productinfo prodclassifytree button[action=upd]':{
	        	click:this.btnUpdClassify
	        },
	        'productinfo prodclassifytree button[action=del]':{
	        	click:this.delClassify
	        },
	        'productinfo prodclassifytree button[action=all]':{
	        	click:this.loadProductAll
	        },
	        'productinfo prodclassifytree':{
	        	itemclick:this.loadProductByClassid
	        },
	        'prodclassifyediter button[action=save]':{
	        	click:this.updateClassify
	        },
	        'productediter button[action=save]':{
	        	click:this.updateProduct
	        },
	        'productediter button[action=addmanuf]':{
	        	click:this.addProdNewManuf
	        },
	        'prodmanufediter button[action=add]':{
	        	click:this.addProdManuf
	        },
	        'prodmanufediter button[action=upd]':{
	        	click:this.btnEditProdManuf
	        },
	        'prodmanufediter button[action=del]':{
	        	click:this.delProdManuf
	        },
	        'prodmanufediter triggerfield':{
	        	specialkey:this.searchProdManuf
	        },
	        'manufediter button[action=save]':{
	        	click:this.updProdManuf
	        },
	        'manufnewediter button[action=save]':{
	        	click:this.updProdNewManuf
	        },
	        'prodmanuflist':{
        		itemdblclick: this.editProdManuf
        	}
        });
    },
    exportXLS:function(btn){
    	 var tree=btn.ownerCt.ownerCt.ownerCt.ownerCt.ownerCt.down('prodclassifytree');
    	var nodes=tree.getSelectionModel().getSelection();
    	var classifyId=1;
    	if(nodes.length == 1){
    		classifyId=nodes[0].get('classifyId');
    	}
    	window.open("base/getProductXLS.do?classifyId="+classifyId);
    },
    refProduct:function(btn){
    	var grid=btn.ownerCt.ownerCt;
    	grid.store.reload();
    },
    showProdProperties:function(grid, record, index, eOpts ){
    	var panel=Ext.ComponentQuery.query('productinfo productlist');
    	
    	var busform=panel[0].ownerCt.down('form');
    	if(!Ext.isEmpty(record.productBusPropertiesHasOneInstance)){
    		busform.loadRecord(record.getproductBusProperties());
    	}
    	else{
    		busform.getForm().reset();
    	}
    	var medicineform=busform.ownerCt.items.items[1];
    	var logisticsform=busform.ownerCt.items.items[2];//暂未实现先添加药物属性
    	if(!Ext.isEmpty(record.productMedicinePropertiesHasOneInstance)){
    		medicineform.loadRecord(record.getproductMedicineProperties());
    		logisticsform.loadRecord(record.getproductMedicineProperties());
    	}
    	else{
    		medicineform.getForm().reset();
    		logisticsform.getForm().reset();
    	}
    },
    loadProductAll:function(btn){
    	var tree=btn.ownerCt.ownerCt;
    	var prodlist=tree.ownerCt.ownerCt.down('productlist');
    	prodlist.store.on("beforeload",function(){
	        Ext.apply(prodlist.store.proxy,{url:'base/getprodbyclassify.do'});
	        Ext.apply(prodlist.store.proxy.extraParams, {classifyId:1});
	    });
     	prodlist.store.load({
     		url:'base/getprodbyclassify.do',
     		params:{classifyId:1},
    		callback:function(records, operation, success){
		    	//
    		},
	   		scope: this
     	});
    },
    loadProductByClassid:function(tree, record, item, index, e, eOpts ){
    	var classifyId=record.get('id');
     	var prodlist=tree.ownerCt.ownerCt.down('productlist');
     	prodlist.store.on("beforeload",function(){
	        Ext.apply(prodlist.store.proxy,{url:'base/getprodbyclassify.do'});
	        Ext.apply(prodlist.store.proxy.extraParams, {classifyId:classifyId});
     		//prodlist.store.proxy.setUrl('base/getprodbyclassify.do');
	    });
	    
     	prodlist.store.loadPage(1,{
     		url:'base/getprodbyclassify.do',
     		params:{classifyId:classifyId},
    		callback:function(records, operation, success){
		    	//
    		},
	   		scope: this
     	});
    },
    addClassify:function(btn){
    	var tree=btn.ownerCt.ownerCt;
    	var nodes=tree.getSelectionModel().getSelection();
    	if(nodes.length == 1){
    		var node = nodes[0];
    		var record=Ext.create('TS.model.base.ProductClassifyModel');
	        var view = Ext.widget('prodclassifyediter');
			view.setParentName(node.get('classifyName'));
			record.set('parentId',node.get('classifyId'))
	    	view.down('form').loadRecord(record);
	    	view.show();
    	}else{
			Ext.Msg.alert('提示','请选择一个上级节点');
		}
        
    },
    btnUpdClassify:function(btn){
    	var tree=btn.ownerCt.ownerCt;
    	var nodes=tree.getSelectionModel().getSelection();
    	if(nodes.length == 1){
			var node = nodes[0];
			var view = Ext.widget('prodclassifyediter');
			if(!Ext.isEmpty(node.parentNode)){
				view.setParentName(node.parentNode.get('classifyName'));
			}
        	view.down('form').loadRecord(node);
        	view.show();
		}else{
			Ext.Msg.alert('提示','请您选择一个节点');
		}
    },
    delClassify:function(btn){
    	console.log(btn);
    },
    updateClassify:function(btn){
    	var win    = btn.up('window'),
        form   = win.down('form');
        if(!form.isValid()) return;
        var record = form.getRecord(),
        values = form.getValues();
        //form.getForm().updateRecord(record);
        record.set(values);
	    win.close();
	    var panel=Ext.ComponentQuery.query('productinfo prodclassifytree');
	    
	    Ext.Ajax.request({
				    url:'base/updprodclassify.do',
				    method : 'POST',
				    timeout :3000,
				    params:{classifyId:record.get('classifyId'),parentId:record.get('parentId'),classifyName:record.get('classifyName')},
				    success:function(response){		
				    	var data=Ext.decode(response.responseText);
				    	if(data.success==true){
				    		panel[0].store.load();
				    	}
				    	showExtReturnMsg(response);
				    }
	    });
    },
    addProd:function(btn){
    	var tree=btn.ownerCt.ownerCt.ownerCt.ownerCt.ownerCt.down('prodclassifytree');
    	var nodes=tree.getSelectionModel().getSelection();
    	if(nodes.length == 1){
    		var record=Ext.create('TS.model.base.ProductModel');
			record.set('classifyId',nodes[0].get('classifyId'));
			record.set('deleted',false);
			record.set('qtyScale',0);
			record.set('priceScale',2);
			record.set('taxRate',0.17);
			var view = Ext.widget('productediter');
	    	view.down('form').loadRecord(record);//加载基本属性
	    	var busform=view.items.items[1];//加载业务属性
	    	if(!Ext.isEmpty(record.productBusPropertiesHasOneInstance)){
	    		busform.loadRecord(record.getproductBusProperties());
	    	}
	    	else{
	    		//没有业务属性新建一个空的
	    		var bus=Ext.create('TS.model.base.ProductBusPropertiesModel');
	    		bus.set('productId',record.get('productId'))
	    		busform.loadRecord(bus);
	    	}
	    	var medicineform=view.items.items[2];//加载药物属性
	    	if(!Ext.isEmpty(record.productMedicineProperteisHasOneInstance)){
	    		medicineform.loadRecord(record.getproductMedicineProperteis());
	    	}else{
	    		//没有药物属性新建一个空的
	    		var med=Ext.create('TS.model.base.ProductMedicinePropertiesModel');
	    		med.set('productId',record.get('productId'))
	    		medicineform.loadRecord(med);
	    	}
	    	view.show();
    	}else{
    		Ext.Msg.alert('提示','新增商品请先点商品类别后再添加');
    	}
		
    },
    delProd:function(btn){
    	var grid = btn.ownerCt.ownerCt;
    	//获取选择的行集合.即record数组
		var data = grid.getSelectionModel().getSelection();
		if(data.length == 0){
			Ext.Msg.alert("提示","您最少要选择一条数据");
		}else{
			Ext.Msg.confirm('删除','真的要删除所选择的商品吗?',function(b){
				if(b=='yes'){
					//1.先得到ID的数据(productId)
					var st = grid.getStore();
					var ids = [];
					Ext.Array.each(data,function(record){
						ids.push(record.get('productId'));
					});
					//2.后台操作(delProduct)
					Ext.Ajax.request({
						url:'base/delProduct.do',
						params:{ids:ids.join(",")},
						method:'POST',
						timeout:3000,
						success:function(response,opts){
							//3.前端操作DOM进行删除(ExtJs)
							var rs=Ext.decode(response.responseText);
					    	if(rs.success==true){
					    		Ext.Array.each(data,function(record){
									st.remove(record);
								});
					    	}
					    	showExtReturnMsg(response);
						}
					});
				}
			});
		}
    },
    btnUpdProd:function(btn){
    	var grid=btn.ownerCt.ownerCt;
    	var data=grid.getSelectionModel().getSelection();
    	if(data.length == 0){
			Ext.Msg.alert("提示","您最少要选择一条数据");
		}else{
			var record=data[0];
			var view = Ext.widget('productediter');
        	view.down('form').loadRecord(record);//加载基本属性
        	var busform=view.items.items[1];//加载业务属性
        	if(!Ext.isEmpty(record.productBusPropertiesHasOneInstance)){
	    		busform.loadRecord(record.getproductBusProperties());
	    	}
	    	else{
	    		//没有业务属性新建一个空的
	    		var bus=Ext.create('TS.model.base.ProductBusPropertiesModel');
	    		bus.set('productId',record.get('productId'))
	    		busform.loadRecord(bus);
	    	}
	    	var medicineform=view.items.items[2];//加载药物属性
	    	if(!Ext.isEmpty(record.productMedicineProperteisHasOneInstance)){
	    		medicineform.loadRecord(record.getproductMedicineProperteis());
	    	}else{
	    		//没有药物属性新建一个空的
	    		var med=Ext.create('TS.model.base.ProductMedicinePropertiesModel');
	    		med.set('productId',record.get('productId'))
	    		medicineform.loadRecord(med);
	    	}
        	view.show();
		}
    },
    updateProduct:function(btn){
    	var win    = btn.up('window'),
        form   = win.down('form');
        
        
        var busform=win.items.items[1];
        var medicineform=win.items.items[2];
        //非空检查
        if(!form.isValid() || !busform.isValid() || !medicineform.isValid())
        {
        	return;
        }
        var record = form.getRecord(),
        values = form.getValues();
        record.set(values);
        var busRecord;
        if(!Ext.isEmpty(record.productBusPropertiesHasOneInstance)){
    		record.getproductBusProperties().set(busform.getValues());
	    }else{
	    	busRecord=busform.getRecord();
	    	busform.getForm().updateRecord(busRecord);  	
	    }
	    
	    var medRecord;
        if(!Ext.isEmpty(record.productMedicineProperteisHasOneInstance)){
	    	record.getproductMedicineProperteis().set(medicineform.getValues());
	    }else{
	    	medRecord=medicineform.getRecord();
	    	medicineform.getForm().updateRecord(medRecord);
	    }
        
	    win.close();
	    var panel=Ext.ComponentQuery.query('productinfo productlist');
	    var data=record.getData(true);
	    delete data.productClassify;//删除 JSON 中的productClassify属性
	    
	    if(!Ext.isEmpty(busRecord)){
	    	data.productBusProperties=busRecord.data;//新增业务属性
	    }
	    if(!Ext.isEmpty(medRecord)){
	    	data.productMedicineProperteis=medRecord.data;//新增药物属性
	    }
	    Ext.Ajax.request({
				    url:'base/updproduct.do',
				    method : 'POST',
				    timeout :3000,
				    jsonData:data,
				    success:function(response){		
				    	var data=Ext.decode(response.responseText);
				    	if(data.success==true){
				    		panel[0].store.reload();
				    	}
				    	showExtReturnMsg(response);
				    }
	    });
    },
    searchProduct:function(field,e){
    	if(e.keyCode==e.ENTER){
	    	var view=Ext.create('TS.view.base.ProductSearchDialog');
	    	view.setVal(field.value);
	    	view.on({
			    selected: function(records){
			    	var panel=field.ownerCt.ownerCt;
			    	panel.store.loadRecords(records);
			    	//panel.store.reload();
			    },
			    scope: this
			});
	    	view.show();
    	}
    },
    productManuf:function(btn){
    	var win=Ext.create('TS.view.base.ProductManufEditer')
    	win.show();
    },
    addProdManuf:function(btn){
		var record=Ext.create('TS.model.base.ProductManufModel');
        var view = Ext.widget('manufediter');
    	view.down('form').loadRecord(record);
    	view.show();
    },
    addProdNewManuf:function(btn){
		var record=Ext.create('TS.model.base.ProductManufModel');
        var view = Ext.widget('manufnewediter');
    	view.down('form').loadRecord(record);
    	view.show();
    },
    updProdNewManuf:function(btn){
    	var win    = btn.up('window'),
        form   = win.down('form');
        if(!form.isValid()) return;
        var record = form.getRecord(),
        values = form.getValues();
        //form.getForm().updateRecord(record);
        record.set(values);
	    win.close();
	    //productediter
	    var prod=Ext.ComponentQuery.query('productediter');
	    Ext.Ajax.request({
				    url:'base/updprodmanuf.do',
				    method : 'POST',
				    timeout :3000,
				    jsonData:record.data,
				    success:function(response){		
				    	var data=Ext.decode(response.responseText);
				    	if(data.success==true){
				    		prod[0].down('textfield[name=manufId]').getStore().reload();
				    		prod[0].down('textfield[name=manufId]').setValue(data.o.manufId);
				    		prod[0].down('textfield[name=manuf]').setValue(record.get('manufName'));
				    	}else{
				    		Ext.Msg.show({title:'ThinkGSP',msg:'添加生产企业出错!',buttons:Ext.Msg.OK,icon:Ext.Msg.WARNING});
				    	}
				    }
	    });
    },
    btnEditProdManuf:function(btn){
    	var grid=btn.ownerCt.ownerCt;
    	var data=grid.getSelectionModel().getSelection();
    	if(data.length == 0){
			Ext.Msg.alert("提示","您最少要选择一条数据");
		}else{
			var record=data[0];
			var view = Ext.widget('manufediter');
        	view.down('form').loadRecord(record);
        	view.show();
		}
    },
    editProdManuf:function(grid,record){
    	var view = Ext.widget('manufediter');
    	view.down('form').loadRecord(record);
    	view.show();
    },
    delProdManuf:function(btn){
    	
    },
    updProdManuf:function(btn){
    	var win    = btn.up('window'),
        form   = win.down('form');
        if(!form.isValid()) return;
        var record = form.getRecord(),
        values = form.getValues();
        //form.getForm().updateRecord(record);
        record.set(values);
	    win.close();
	    var panel=Ext.ComponentQuery.query('prodmanufediter prodmanuflist');
	    
	    Ext.Ajax.request({
				    url:'base/updprodmanuf.do',
				    method : 'POST',
				    timeout :3000,
				    jsonData:record.data,
				    success:function(response){		
				    	var data=Ext.decode(response.responseText);
				    	if(data.success==true){
				    		panel[0].store.commitChanges();
				    		panel[0].store.reload();
				    	}else{
				    		panel[0].store.rejectChanges();
				    	}
				    	showExtReturnMsg(response);
				    }
	    });
    },
    searchProdManuf:function(field,e){
    	if(e.keyCode==e.ENTER){
	    	var val=field.value;
	    	var panel=field.ownerCt.ownerCt;
	    	panel.store.load({
	    	url:'base/searchmanuf.do',
	     		params:{val:val},
	    		callback:function(records, operation, success){
			    	//
	    		},
		   		scope: this
	    	})
    	}
    },
    recycleProd:function(btn){
    	var grid=btn.ownerCt.ownerCt;
    	grid.store.load({
    		url:'base/recycleProd.do',
    		callback:function(records, operation, success){
    			if(success==false)
    				Ext.Msg.show({title:'ThinkGSP',msg:'查询回收站数据出错!',buttons:Ext.Msg.OK,icon:Ext.Msg.WARNING});
    		},
	   		scope: this
    	})
    },
    restoreProd:function(btn){
    	var grid=btn.ownerCt.ownerCt;
    	var data=grid.getSelectionModel().getSelection();
    	if(data.length == 0){
    		Ext.Msg.show({title:'ThinkGSP',msg:'您最少要选择一条数据!',buttons:Ext.Msg.OK,icon:Ext.Msg.WARNING});
		}else{
			var st=grid.getStore();
			Ext.Ajax.request({
				url:'base/restoreProd.do',
				params:{productId:data[0].get("productId")},
				method:'POST',
				timeout:3000,
				success:function(response,opts){
					//3.前端操作DOM进行删除(ExtJs)
					var rs=Ext.decode(response.responseText);
			    	if(rs.success==true){
			    		Ext.Array.each(data,function(record){
			    			if(record.get('deleted'))
								st.remove(record);
						});
			    	}
			    	showExtReturnMsg(response);
					
				}
			});
		}
    }
});

